package com.xiangxiangjd.config.dictutils;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xiangxiangjd.bean.SysDict;
import com.xiangxiangjd.service.SysDictService;
import freemarker.core.Environment;
import freemarker.template.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
 * @author LF
 * @date 2020/9/2 - 11:29
 *
 */
@Component
public class DictDirective implements TemplateDirectiveModel {


    @Autowired
    SysDictService sysDictService;

    @Override
    public void execute(Environment environment, Map map, TemplateModel[] templateModels, TemplateDirectiveBody templateDirectiveBody) throws TemplateException, IOException, IOException {
        DefaultObjectWrapperBuilder builder = new DefaultObjectWrapperBuilder(Configuration.VERSION_2_3_25);

        if(map.containsKey("type") && map.get("type") != null){
            String type = map.get("type").toString();
            /*List<Dict> dictList = DictUtils.getDictList(type);*/

            QueryWrapper<SysDict> queryWrapperSdf = new QueryWrapper<>();
            queryWrapperSdf.lambda().eq(SysDict::getType, type);

            List<SysDict> dictList = sysDictService.list(queryWrapperSdf);

            if(map.containsKey("value") && map.get("value") != null){
                String value = map.get("value").toString();
                SysDict dict = null;
                for (SysDict dict1 : dictList) {
                    if(value.equals(dict1.getK())){
                        dict = dict1;
                    }
                }
                environment.setVariable("dict", builder.build().wrap(dict));
            }else{
                environment.setVariable("dictList", builder.build().wrap(dictList));
            }
        }
        if(templateDirectiveBody!=null){
            templateDirectiveBody.render(environment.getOut());
        }
    }
}
